<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { DirectionalCheckApi, GetCheckResultsApi, EditCheckResultApi } from '@/api/assessment'
import { getPalyFileApi } from '@/api/table'
import { getTreeDepartmentsApi } from '@/api/department'
import { ref, unref, reactive } from 'vue'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import DPlayer from 'dplayer'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const { push } = useRouter()
const { t } = useI18n()
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'depName',
    label: t('userDemo.department')
  },

  // {
  //   field: 'fileName',
  //   label: t('common.fileName')
  // },
  // {
  //   field: 'filePath',
  //   label: t('common.filePath')
  // },
  {
    field: 'assessmentType',
    label: '抽查类型'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => look(data.row)}>
              {t('exampleDemo.detail')}
            </BaseButton>
            {/* <BaseButton type="danger" onClick={() => delData(data.row)}>
              {t('exampleDemo.del')}
            </BaseButton> */}
          </>
        )
      }
    }
  }
]

interface files {
  guid: string
  filePath: string
  fileName: string
}

const showDetail = ref(false)
let saveLoading = ref(false)
const showVideoLoading = ref(false)
let currentRow = ref<files | null>(null)
let videoUrl = ref()
const videoRef = ref()
const look = async (row) => {
  //: files
  showDetail.value = true
  showVideoLoading.value = true
  currentRow.value = row

  getPalyFileApi({ fileGuid: row.fileGuid })
    .then((res) => {
      videoUrl.value = res.data
      // const videoFile = new Blob([res.data], {
      //   type: 'video/mp4'
      // })
      // videoUrl.value = URL.createObjectURL(videoFile)
      // console.log('videoUrl.value---', unref(videoUrl.value))
      // const dp = new DPlayer({
      //   container: videoRef.value,
      //   autoplay: true,
      //   theme: '#FADFA3',
      //   loop: true,
      //   lang: 'zh-cn',
      //   screenshot: true,
      //   hotkey: true,
      //   preload: 'auto',
      //   // logo: 'logo.png',
      //   volume: 0.7,
      //   mutex: true,
      //   video: {
      //     url: videoUrl.value,
      //     type: 'flv'
      //   }
      // })

      showVideoLoading.value = false
    })
    .catch(() => {
      showVideoLoading.value = false
      ElMessage({
        message: '视频加载失败',
        type: 'error'
      })
    })
}

// push({ path: '/assessment/assessment', query: { assessmentGuid: row.assessmentGuid } })

const departmentList = ref([])
const fetchDepartment = async () => {
  const res = await getTreeDepartmentsApi({})
  departmentList.value = res.data
}
fetchDepartment()
const showForm = ref(true)
const getCurrentMonthDates = () => {
  const currentDate = new Date()
  const firstDay = new Date(currentDate.setDate(1))
  const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0)
  const year = firstDay.getFullYear() //获取当前年
  const month = String(firstDay.getMonth() + 1).padStart(2, '0') //获取当前月
  const lastDayOfMonth = lastDay.getDate() //获取当前月的天
  return [`${year}-${month}-01 00:00:00`, `${year}-${month}-${lastDayOfMonth} 23:59:59`]
}
const defaultTime = ref(getCurrentMonthDates())
const formSchema = reactive<FormSchema[]>([
  {
    field: 'depGuid',
    label: t('userDemo.department'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'guid',
      props: {
        label: 'depName',
        value: 'guid',
        children: 'children'
      },
      placeholder: '请选择部门',
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      defaultExpandAll: true,
      filterable: true
      // showSearch: true,
      // filterable: true,
      // filterMethod: (value: string, data: any) => {
      //   if (!value) return true
      //   return data.depName.indexOf(value) !== -1
      // },
      // options: departmentList.value
    },
    optionApi: async () => {
      return departmentList.value || []
    }
  },
  // {
  //   field: 'randomCount',
  //   label: '抽查数量',
  //   component: 'Input',
  //   componentProps: {
  //     placeholder: '请输入抽查数量',
  //     type: 'number'
  //   }
  // },
  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    value: defaultTime.value,
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date',
      value: defaultTime.value
    }
  }
])

const rules = reactive({
  depGuid: [required()],
  randomCount: [required()],
  date: [required()]
})
const dataList = ref([])
const loading = ref(false)
const createAssessment = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    loading.value = true
    console.log(formData)
    if (formData) {
      if (formData.date) {
        formData.startTime = formData.date[0]
        formData.endTime = formData.date[1]
        delete formData.date
      }
      saveLoading.value = true
      let res = await DirectionalCheckApi(formData).finally(() => {
        saveLoading.value = false
      })

      if (res) {
        dataList.value = res.data || []
        loading.value = false
        showForm.value = false
      }
    }
  }
}

const formSchemaDialog = ref<FormSchema[]>([
  {
    field: 'score',
    label: '评分',
    component: 'Input',
    componentProps: {
      placeholder: '请输入',
      type: 'number'
    }
  },
  {
    field: 'detailContent',
    label: '评价内容',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '180px' }
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '120px' }
    }
  }
])
const rulesDialog = reactive({
  score: [required()],
  detailContent: [required()]
})

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log(formData, currentRow)
    if (formData) {
      saveLoading.value = true
      let res = await EditCheckResultApi({ ...currentRow.value, ...formData }).finally(() => {
        saveLoading.value = false
      })

      if (res) {
        showDetail.value = false
      }
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div v-if="showForm" title="请选择抽查目标" :fullscreen="false" :isShowClose="false">
      <Form :rules="rules" @register="formRegister" :schema="formSchema" />
      <BaseButton type="primary" :loading="saveLoading" @click="createAssessment">
        确定
      </BaseButton>
    </div>
    <Table :reserveIndex="true" :columns="columns" :data="dataList" :loading="loading" v-else />

    <Dialog v-model="showDetail" title="详情">
      <div class="row_d">
        <!-- <div ref="videoRef" style="width: 400px; height: 400px" v-loading="showVideoLoading"></div> -->
        <video
          :src="videoUrl"
          ref="videoRef"
          controls
          style="width: 400px; height: 400px; background: #000"
          preload="auto"
          autoplay
          v-loading="showVideoLoading"
        ></video>
        <div class="rombox">
          <Form
            :rules="rulesDialog"
            @register="formRegister"
            :schema="formSchemaDialog"
            :isCol="false"
            ref="writeRef"
          />
        </div>
      </div>
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="showDetail = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
.dplayer-menu :deep(.dplayer-mask) {
  display: none !important;
}
.row_d {
  display: flex;
  /* align-items: center; */
}
.rombox {
  width: 500px;
  margin-left: 20px;
}
.downstyle {
  margin-right: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 500;
  -webkit-user-select: none;
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: #529b2e;
  border: var(--el-border);
  border-color: #529b2e;
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  text-decoration: none;
}
:deep(.el-row) {
  flex-direction: column !important;
}
</style>
